package com.dchat.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dchat.domain.ResponseDto;
import com.dchat.domain.User;
import com.dchat.domain.UserInfo;
import com.dchat.service.inter.FriendService;
import com.dchat.service.inter.UserService;
import com.dchat.util.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 有关于好友的接口在这里实现
 */
@RestController
@RequestMapping("/dchat")
public class FriendController {
    @Autowired
    private RedisOperator redisOperator;
    @Autowired
    private FriendService friendService;
    @Autowired
    private UserService userService;

    @PostMapping("/getFriendList")
    public String getFriendList(@RequestBody String data){
        JSONObject jsonObject = JSONUtil.parseObj(data);
        //验证token是否存在或者失效
        Integer id = redisOperator.verifyToken(jsonObject.getStr("token"));
        if(id==null) {
            return JSONUtil.toJsonStr(new ResponseDto<String>(false, 404, "token失效或者未找到"));
        }

        List<UserInfo> list = friendService.getFriendsById(id);
        return JSONUtil.toJsonStr(new ResponseDto<>(list));
    }

    @PostMapping("/findPerson")
    public String findPerson(@RequestBody String data){
        JSONObject jsonObject = JSONUtil.parseObj(data);
        User user = userService.getUserById(Integer.valueOf(jsonObject.getStr("id")));
        if(null==user){
            return JSONUtil.toJsonStr(new ResponseDto<>("not found"));
        }
        return JSONUtil.toJsonStr(new ResponseDto<>(new UserInfo(user)));
    }

    @PostMapping("/findPeople")
    public String findPeople(@RequestBody String data){
        JSONObject jsonObject = JSONUtil.parseObj(data);
//        //验证token是否存在或者失效
//        Integer id = redisOperator.verifyToken(jsonObject.getStr("token"));
//        if(id==null) {
//            return JSONUtil.toJsonStr(new ResponseDto<String>(false, 404, "token失效或者未找到"));
//        }


        String keyword = jsonObject.getStr("keyword");
        keyword = keyword.replaceAll("%","\\\\%").replaceAll("_","\\\\_");

        List<User> userList = userService.selectByKeyword(keyword);
        List<UserInfo> userInfoList = new ArrayList<>();
        for(User user:userList){
            userInfoList.add(new UserInfo(user));
        }
        return JSONUtil.toJsonStr(new ResponseDto<>(userInfoList));
    }
}
